const axios = require("axios");
const fs = require("fs");
const FormData = require("form-data");

const getModules = require("./getModules");
const {
  ATOMGIT_ADMIN_COOKIE,
  MODULE_DIST_DIR,
  UPLOAD_URL,
  ATOMGIT_MICRO_CACHE_FILE,
} = require("./config");

const allModules = getModules({
  dir: MODULE_DIST_DIR,
  ossPrefix: "uploads/assets",
  generateCacheFile: false,
  cacheFileName: ATOMGIT_MICRO_CACHE_FILE,
});

console.log("待上传文件列表", allModules);
console.log(
  "待上传文件总数：",
  allModules.filter((item) => item.isHashDiff).length
);

const adminUpload = async (fileInfo) => {
  const submitData = new FormData();
  submitData.append("path", fileInfo.path);
  submitData.append("file", fs.createReadStream(fileInfo.file));
  try {
    const res = await axios({
      method: "post",
      url: UPLOAD_URL,
      data: submitData,
      headers: {
        Cookie: ATOMGIT_ADMIN_COOKIE,
        Connection: "keep-alive",
        ...submitData.getHeaders(),
      },
    });
    console.log("已上传：", res.data);
  } catch (e) {
    console.error("上传错误:", e);
  }
};

// 批量上传
async function multiUpload() {
  try {
    console.log("======开始上传========");
    console.time();
    while (allModules.length > 0) {
      const item = allModules.shift();
      if (item.isHashDiff) {
        console.log("需要上传", item.path);
        await adminUpload(item);
      }
    }
    console.log("======全部上传完成======");
    console.timeEnd();

    // 更新 cache 文件
    getModules({
      dir: MODULE_DIST_DIR,
      ossPrefix: "uploads/assets",
      generateCacheFile: true,
      cacheFileName: ATOMGIT_MICRO_CACHE_FILE,
    });
  } catch (e) {
    console.error("批量上传过程中发生错误:", e);
  }
}

multiUpload();
